<template>
  <div class="editor-container">
    <!-- 格式工具栏 -->
    <div class="toolbar">
      <select v-model="fontFamily" @change="formatText('fontName', fontFamily)">
        <option value="Arial">Arial</option>
        <option value="Times New Roman">Times New Roman</option>
        <option value="Microsoft YaHei">微软雅黑</option>
      </select>

      <select v-model="fontSize" @change="formatText('fontSize', fontSize + 'pt')">
        <option>10</option>
        <option>12</option>
        <option>14</option>
        <option>16</option>
      </select>

      <button @click="formatText('bold')" :class="{ active: formats.bold }">
        加粗
        <i class="fas fa-bold"></i>
      </button>
      <button @click="formatText('italic')" :class="{ active: formats.italic }">
        斜体
        <i class="fas fa-italic"></i>
      </button>
      <button @click="formatText('underline')">
        下划线
        <i class="fas fa-underline"></i>
      </button>

      <ColorPicker @change="color => formatText('foreColor', color)" />

      <div class="alignment">
        <button @click="formatText('justifyLeft')">
          <i class="fas fa-align-left"></i>
        </button>
        <button @click="formatText('justifyCenter')">
          <i class="fas fa-align-center"></i>
        </button>
        <button @click="formatText('justifyRight')">
          <i class="fas fa-align-right"></i>
        </button>
      </div>

      <!-- 新增导出按钮 -->
      <button @click="exportToWord">导出为 Word</button>
    </div>

    <!-- 编辑区域 -->
    <div 
      class="editor-content"
      ref="editor"
      contenteditable="true"
      @input="onContentChange"
      @mouseup="getSelectionFormat"
    ></div>

    <!-- 状态栏 -->
    <div class="status-bar">
      字数: {{ wordCount }} | 语言: 中文(中国)
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import ColorPicker from '../components/ColorPicker.vue'
import { saveAs } from 'file-saver'
import { Document, Packer, Paragraph, TextRun } from 'docx'

const editor = ref(null)
const content = ref('')
const wordCount = ref(0)
const fontFamily = ref('Arial')
const fontSize = ref(12)
const formats = ref({
  bold: false,
  italic: false,
  underline: false
})

const formatText = (command, value = null) => {
  document.execCommand(command, false, value)
  getSelectionFormat()
}

const getSelectionFormat = () => {
  const selection = document.getSelection()
  if (!selection.rangeCount) return
  
  formats.value = {
    bold: document.queryCommandState('bold'),
    italic: document.queryCommandState('italic'),
    underline: document.queryCommandState('underline')
  }
}

const onContentChange = () => {
  content.value = editor.value.innerHTML
  wordCount.value = editor.value.innerText.replace(/\s+/g, '').length
}

onMounted(() => {
  editor.value.focus()
})

const exportToWord = async () => {
  const content = editor.value.innerHTML
  const doc = new Document({
    creator: 'Your Name',
    title: 'Exported Document',
    description: 'This is an exported document from the editor.'
  })

  const parser = new DOMParser()
  const docHtml = parser.parseFromString(content, 'text/html')

  const sections = []; // 创建一个 sections 数组
  docHtml.body.querySelectorAll('p, div').forEach(block => {
    const paragraph = new Paragraph({
      children: processNodes(block.childNodes)
    })
    sections.push({ children: [paragraph] }); // 将每个段落添加到 sections 数组中
  })

  // 将 sections 数组添加到文档中
  doc.addSection(sections);

  const blob = await Packer.toBlob(doc)
  saveAs(blob, 'document.docx')
}

const processNodes = (nodes) => {
  return Array.from(nodes).map(node => {
    if (node.nodeType === Node.TEXT_NODE) {
      return new TextRun({ text: node.textContent.trim() })
    }
    
    if (node.nodeType === Node.ELEMENT_NODE) {
      const style = window.getComputedStyle(node)
      return new TextRun({
        text: node.textContent.trim(),
        bold: style.fontWeight === 'bold',
        italic: style.fontStyle === 'italic',
        color: style.color.replace(/#/g, ''),
        size: parseInt(style.fontSize) * 2, // 转换为半磅值
        font: style.fontFamily.split(',')[0].trim()
      })
    }
  }).filter(Boolean)
}
</script>


<style scoped>

.icon {
  width: 20px;
  height: 20px;
  fill: currentColor;
}

.editor-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  padding: 10px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

button {
  padding: 5px 10px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 3px;
}

button.active {
  background: #e9ecef;
}

select {
  padding: 5px;
  border: 1px solid #ddd;
}

.editor-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  border: none;
  outline: none;
  font-family: v-bind(fontFamily);
  font-size: v-bind(fontSize + 'pt');
  background: white;
  color: #333;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 4px;
  margin: 10px;
  min-height: 400px;
}

.status-bar {
  padding: 5px 10px;
  background: #f8f9fa;
  border-top: 1px solid #dee2e6;
  font-size: 0.9em;
  color: #6c757d;
}

</style>